package com.aacar.op.service.security;

import com.aacar.op.utils.Collections3;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 抽象出授权类
 *
 * @author Gongle
 */
public abstract class AuthorizationRealm extends AuthorizingRealm {
    private static Logger logger = LoggerFactory.getLogger(AuthorizationRealm.class);


    @PostConstruct
    public void initBeans() {
        logger.debug("Apache Shiro 授权类");
    }


    /**
     * 授权权限、角色方法
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        ShiroUser user = (ShiroUser) principals.getPrimaryPrincipal();
        logger.debug("授权权限:{}", user.getPermissionList());
        addPermissions(info, user.getPermissionList());
        return info;
    }

    private void addPermissions(final SimpleAuthorizationInfo info, List<String> permList) {

        if (Collections3.isNotEmpty(permList)) {
            List<String> permListAfterClean = Lists.newArrayList();
            for (String s : permList) {
                if (StringUtils.isBlank(s)) {
                    continue;
                }

                permListAfterClean.add(s);
            }
            //将当前用户拥有的permissions设置到SimpleAuthorizationInfo中
            info.addStringPermissions(permListAfterClean);
        }
    }


}
